using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    [Header("跟随目标")] public Transform target; // 要跟随的角色

    [Header("相机设置")] public float distance = 5.0f; // 相机与目标的距离
    public float minDistance = 2.0f; // 最小距离
    public float maxDistance = 10.0f; // 最大距离
    public float height = 2.0f; // 相机的高度
    public float lookAtHeight = 1.0f; // 相机注视点的高度

    [Header("平滑设置")] public float smoothSpeed = 0.125f; // 相机跟随的平滑度
    public float zoomSpeed = 1.0f; // 缩放速度

    [Header("旋转设置")] public bool allowRotation = true; // 是否允许旋转
    public float rotationSpeed = 2.0f; // 旋转速度
    public float minVerticalAngle = -40f; // 垂直旋转的最小角度
    public float maxVerticalAngle = 80f; // 垂直旋转的最大角度

    private float _currentRotationX = 0f; // 当前X轴旋转角度
    private float _currentRotationY = 0f; // 当前Y轴旋转角度

    void Start()
    {
        // 初始化相机位置和旋转
        if (target != null)
        {
            Vector3 targetPosition = target.position - Quaternion.Euler(_currentRotationX, _currentRotationY, 0) *
                (Vector3.forward * distance) + Vector3.up * height;
            transform.position = targetPosition;
            transform.LookAt(target.position + Vector3.up * lookAtHeight);
        }
    }

    void LateUpdate()
    {
        if (target == null) return;

        // 处理滚轮缩放
        float scrollInput = Input.GetAxis("Mouse ScrollWheel");
        if (scrollInput != 0)
        {
            distance -= scrollInput * zoomSpeed;
            distance = Mathf.Clamp(distance, minDistance, maxDistance);
        }

        // 处理旋转输入
        if (allowRotation && Input.GetMouseButton(1)) // 右键拖拽
        {
            _currentRotationY += Input.GetAxis("Mouse X") * rotationSpeed;
            _currentRotationX -= Input.GetAxis("Mouse Y") * rotationSpeed;
            _currentRotationX = Mathf.Clamp(_currentRotationX, minVerticalAngle, maxVerticalAngle);
        }

        // 计算相机的目标位置
        Quaternion rotation = Quaternion.Euler(_currentRotationX, _currentRotationY, 0);
        Vector3 targetPosition = target.position - rotation * (Vector3.forward * distance) + Vector3.up * height;

        // 平滑移动相机到目标位置
        transform.position = Vector3.Lerp(transform.position, targetPosition, smoothSpeed);

        // 让相机看向目标
        transform.LookAt(target.position + Vector3.up * lookAtHeight);
    }
}